package com.moweilin.mo_gateway.services.impl;

import com.moweilin.mo_gateway.exceptions.DuplicateKeyException;
import com.moweilin.mo_gateway.handlers.Module;
import com.moweilin.mo_gateway.services.IModuleService;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by moweilin on 2017/2/23.
 */
public class SimpleModuleService implements IModuleService {
    public static final String DEFAULT_MODULE_NAME = "main";
    private String defaultModuleName = DEFAULT_MODULE_NAME;
    private static IModuleService instance;
    private Map<String,Module> moduleMap;
    private SimpleModuleService() {
        moduleMap = new HashMap<>();
    }

    public static IModuleService getInstance(){
        if(instance == null){
            instance = new SimpleModuleService();
        }
        return instance;
    }

    /**
     *
     * @param moduleName
     * @return
     *
     *  path   http://host/module/request
     *  module key:
     *      /
     *      /module
     *
     */
    @Override
    public Module get(String moduleName) {
        moduleName = StringUtils.defaultString(moduleName);
        if(!moduleMap.containsKey(moduleName)){
            moduleName = defaultModuleName;
        }
        return moduleMap.get(moduleName);
    }


    @Override
    public Module add(Module module) {
        String moduleKey = module.getName();
        if(moduleMap.containsKey(moduleKey)){
            throw new DuplicateKeyException("module [" + moduleKey+"] already exists.");
        }
        return moduleMap.put(moduleKey,module);
    }

    @Override
    public Module update(Module module) {
        return moduleMap.put(module.getName(),module);
    }

    @Override
    public Module delete(String moduleName) {
        moduleName = StringUtils.defaultString(moduleName);
        return moduleMap.remove(moduleName);
    }
}
